package com.halfsword.creativecraft.block.custom.machine;

import com.halfsword.creativecraft.block.custom.machine.blockentity.SteamPowerCrusherBlockEntity;
import com.halfsword.creativecraft.block.custom.machine.blockentity.TileEntities;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.network.NetworkHooks;
import org.jetbrains.annotations.Nullable;

public class SteamPowerCrusherMachineBlock extends BaseBlockEntityBlock {

    public SteamPowerCrusherMachineBlock(BlockBehaviour.Properties properties) {
        super(properties);
    }

    // ==== 方块实体创建 ==== //
    @Override
    public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {
        return new SteamPowerCrusherBlockEntity(pos, state);
    }

    // ==== Ticker 实现 ==== //
    @Nullable
    @Override
    public <T extends BlockEntity> BlockEntityTicker<T> getTicker(
            Level level, BlockState state, BlockEntityType<T> type) {

        if (level.isClientSide()) {
            return null;
        }

        return createTickerHelper(
                type,
                TileEntities.STEAM_POWER_CRUSHER_BE.get(),
                (lvl, pos, st, be) -> be.tick(lvl, pos, st)
        );
    }

    // ==== 重写特定行为 ==== //
    @Override
    protected void handleBlockEntityDrops(Level level, BlockPos pos, BlockEntity blockEntity) {
        if (blockEntity instanceof SteamPowerCrusherBlockEntity machine) {
            machine.drops();
        }
    }

    @Override
    protected InteractionResult handleBlockEntityInteraction(ServerPlayer player, BlockPos pos, BlockEntity blockEntity) {
        if (blockEntity instanceof SteamPowerCrusherBlockEntity machine) {
            NetworkHooks.openScreen(player, machine, pos);
            return InteractionResult.CONSUME;
        }
        return InteractionResult.FAIL;
    }

    // ==== 添加加水/盛水功能 ==== //
    @Override
    public InteractionResult use(BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) {
        if (level.isClientSide) {
            return InteractionResult.SUCCESS;
        }

        ItemStack itemStack = player.getItemInHand(hand);
        BlockEntity blockEntity = level.getBlockEntity(pos);

        if (!(blockEntity instanceof SteamPowerCrusherBlockEntity crusher)) {
            return InteractionResult.PASS;
        }

        // 尝试使用流体交互（桶等）- 修复：从 LazyOptional 中获取 IFluidHandler
        crusher.getFluidHandlerModule().getFluidHandler().ifPresent(fluidHandler -> {
            FluidUtil.interactWithFluidHandler(player, hand, fluidHandler);
        });

        // 特殊处理：空瓶加水（如果机器有足够的水）
        if (itemStack.getItem() == Items.GLASS_BOTTLE) {
            int waterNeeded = 250; // 一瓶水需要250mB
            int availableWater = crusher.getFluidHandlerModule().getWaterLevel();

            if (availableWater >= waterNeeded) {
                itemStack.shrink(1);
                crusher.getFluidHandlerModule().extractWater(waterNeeded);

                ItemStack waterBottle = new ItemStack(Items.POTION);
                if (itemStack.isEmpty()) {
                    player.setItemInHand(hand, waterBottle);
                } else if (!player.getInventory().add(waterBottle)) {
                    player.drop(waterBottle, false);
                }
                return InteractionResult.SUCCESS;
            }
        }

        // 默认行为：打开GUI
        if (player instanceof ServerPlayer serverPlayer) {
            NetworkHooks.openScreen(serverPlayer, crusher, pos);
        }

        return InteractionResult.SUCCESS;
    }
}